const { db, query } = require("../db")

// 登录
exports.adminlogin = (req, res, next) => {
  const { username, password } = req.body
  // console.log(req.body)
  const sql = `select * 
               from tb_admins
               where username='${username}' and password='${password}';`
  db.query(sql, function (err, results) {
    if (err || results.length <= 0) {
      // console.log('登陆失败')
      return res.cc({ msg: '账号或密码错误' })
    }
    let userInfo = results[0]
    userInfo.password = ''
    res.cc({
      msg: '登陆成功',
      userInfo
    }, 200)
  })
}

// 获取用户列表
exports.getadminlist= (req, res, next) => {
  const { query } = req.query
  // console.log(req.query)
  const sql = `select * 
               from tb_admins;`
  db.query(sql, function (err, results) {
    // if (err || results.length <= 0) return res.cc({ msg: '无用户' })
    let list = []
    for (let i=0; i<results.length; i++) {
      if (results[i].username.indexOf(query) !== -1 || results[i].password.indexOf(query) !== -1) {
        list.push(results[i])
      }
    }
    res.cc({
      msg: '查找成功',
      adminlist: list
    }, 200)
  })
}

// 添加/修改管理员
exports.setadmininfo = async (req, res, next) => {
  const { username, password, isAdd } = req.body
  if (!isAdd) {
    // 修改管理员
    await query(`update tb_admins set password='${password}' where username='${username}';`)
    res.cc({
      msg: '修改成功'
    }, 200)
  } else {
    // 新添管理员
    let userlist = await query(`select * from tb_admins where username='${username}';`)
    if (userlist.length !== 0) {
      return res.cc({
        msg: '账号已存在'
      })
    }
    await query(`insert into tb_admins (username, password) values('${username}', '${password}');`)
    res.cc({
      msg: '添加成功'
    }, 200)
  }
}

// 删除用户
exports.deladmininfo = async (req, res, next) => {
  const { username } = req.body
  let userlist = await query(`select * from tb_admins where username='${username}';`)
  if (userlist.length !== 0 ) {
    // 删除用户信息
    await query(`delete from tb_admins where username='${username}';`)
    res.cc({
      msg: '删除成功'
    }, 200)
  } else {
    res.cc({
      msg: '无此用户'
    })
  }
}